<script setup>
import { computed, unref } from 'vue'
import { ElIcon } from 'element-plus'
import { useDesign } from '@/hooks/web/useDesign'
import { Icon } from '@iconify/vue'
import { ICON_PREFIX } from '@/constants'

// 接收 props
const props = defineProps({
  icon: {
    type: String,
    default: ''
  },
  color: {
    type: String,
    default: ''
  },
  size: {
    type: Number,
    default: 16
  },
  hoverColor: {
    type: String,
    default: ''
  }
})

const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('icon')

// 是否是本地图标（svg-sprite）
const isLocal = computed(() => props.icon.startsWith('svg-icon:'))

// 本地 symbolId
const symbolId = computed(() => {
  return unref(isLocal) ? `#icon-${props.icon.split('svg-icon:')[1]}` : props.icon
})

// 是否使用在线图标
const isUseOnline = computed(() => import.meta.env.VITE_USE_ONLINE_ICON === 'true')

// iconify 的样式
const getIconifyStyle = computed(() => {
  return {
    fontSize: `${props.size}px`,
    color: props.color
  }
})

// 处理 iconify 名称
const getIconName = computed(() => {
  return props.icon.startsWith(ICON_PREFIX) ? props.icon.replace(ICON_PREFIX, '') : props.icon
})
</script>

<template>
  <ElIcon :class="prefixCls" :size="size" :color="color">
    <svg v-if="isLocal" aria-hidden="true">
      <use :xlink:href="symbolId" />
    </svg>

    <template v-else>
      <Icon v-if="isUseOnline" :icon="getIconName" :style="getIconifyStyle" />
      <div v-else :class="`${icon} iconify`" :style="getIconifyStyle"></div>
    </template>
  </ElIcon>
</template>
<style lang="less" scoped>
@prefix-cls: ~'@{adminNamespace}-icon';

.@{prefix-cls},
.iconify {
  :deep(svg) {
    &:hover {
      color: v-bind(hoverColor) !important;
    }
  }
}

.iconify {
  &:hover {
    color: v-bind(hoverColor) !important;
  }
}
</style>
